//
//  MPSearchResultViewController.m
//  SearchPeople
//
//  Created by zk on 16/5/16.
//
//

#import "MPSearchResultViewController.h"
#import "MPDocumentHttpClient.h"
#import <SVProgressHUD.h>
#import "MPSearchResultTableViewCell.h"
#import "FaceppAPI.h"
#import "MPClueViewController.h"

@interface MPSearchResultViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (strong, nonatomic) NSMutableArray *datasource;
@property (strong, nonatomic) NSMutableArray *searchArray;

@end

@implementation MPSearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.tableFooterView = [UIView new];
    [self getdata];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [SVProgressHUD show];
    
}

#pragma mark - private

- (void)NameSearch{
    [self.searchArray removeAllObjects];
    for (int i = 0; i < self.datasource.count; i++) {
        NSString *name = [NSString stringWithFormat:@"%@",self.datasource[i][@"name"]];
        if ([name rangeOfString:self.name].length > 0) {
            [self.searchArray addObject:self.datasource[i]];
        }
    }
    if (self.searchArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"未搜到相关走失人员"];
        [self.navigationController popViewControllerAnimated:YES];
    }else
    {
        [self.tableview reloadData];
        [SVProgressHUD dismiss];
    }
}

#pragma mark - network

- (void)getdata{
    [[MPDocumentHttpClient shareInstance] GetDocumentWithType:1 WithSuccessBlock:^(MPRequest *request, MPResponse *response) {
        NSDictionary * dic = response.result;
        self.datasource = [dic[@"data"] mutableCopy];
        [[MPDocumentHttpClient shareInstance] GetDocumentWithType:0 WithSuccessBlock:^(MPRequest *request, MPResponse *response) {
            NSDictionary * dic = response.result;
            NSArray *array = dic[@"data"];
            for (NSDictionary *dictionary in array) {
                [self.datasource addObject:dictionary];
            }
            if (self.type == 0) {
                [self SearchData];//图片
            } else {
                [self NameSearch];//人名
            }
        } WithFailedBlock:^(MPRequest *request, MPResponse *response) {
            [SVProgressHUD showErrorWithStatus:REQUEST_FAILE];
        }];
    } WithFailedBlock:^(MPRequest *request, MPResponse *response) {
        [SVProgressHUD showErrorWithStatus:REQUEST_FAILE];
    }];
}

/**
 *  对比获得数据
 */
- (void)SearchData{
    [self.searchArray removeAllObjects];
    FaceppResult *firstResult = [[FaceppAPI detection] detectWithURL:nil orImageData:self.imageData];
    NSArray *array = firstResult.content[@"face"];
    if (array.count > 0) {
        NSString *FirstFaceId = [NSString stringWithFormat:@"%@",firstResult.content[@"face"][0][@"face_id"]];
        for (int i = 0; i < self.datasource.count; i++) {
            NSString *url = self.datasource[i][@"picture"];
            NSURL *imageURL = [NSURL URLWithString:url];
            NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
            FaceppResult *secondResult = [[FaceppAPI detection] detectWithURL:nil orImageData:imageData];
            NSArray *faceArray = secondResult.content[@"face"];
            if (faceArray.count > 0) {
                NSString *SecondFaceId = [NSString stringWithFormat:@"%@",secondResult.content[@"face"][0][@"face_id"]];
                
                FaceppResult *result = [[FaceppAPI recognition] compareWithFaceId1:FirstFaceId andId2:SecondFaceId async:false];
                float similarity = [result.content[@"similarity"] floatValue];
                if (similarity >= 80) {
                    [self.searchArray addObject:self.datasource[i]];
                }
                
            }
        }
        if (self.searchArray.count == 0) {
            [SVProgressHUD showErrorWithStatus:@"未搜到相似图片"];
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            [self.tableview reloadData];
            [SVProgressHUD dismiss];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"请上传人脸图片"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - tableview datasource & delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MPSearchResultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MPSearchResultTableViewCell"];
    [cell configWithData:self.searchArray[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"HomePage" bundle:nil];
    MPClueViewController *targetVC = [story instantiateViewControllerWithIdentifier:@"MPClueViewController"];
    targetVC.dic = self.searchArray[indexPath.row];
    [self.navigationController pushViewController:targetVC animated:YES];
}

#pragma mark - Setter & Getter

- (NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [[NSMutableArray alloc] init];
    }
    return _datasource;
}

- (NSMutableArray *)searchArray{
    if (!_searchArray) {
        _searchArray = [[NSMutableArray alloc] init];
    }
    return _searchArray;
}

@end
